package com.bs.jianli.util.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bs.jianli.util.exception.NoAuthException;
import com.bs.jianli.util.exception.NotUserException;
import com.bs.jianli.util.redis.RedisUtils;
import com.bs.jianli.util.redis.TokenUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 小姚
 * @pakeageName:com.bs.jianli.util.security
 * @ClassName:SecurityFilter
 * @Descirption:
 * @data 2023/1/14 0:16
 */
@Component
public class SecurityFilter extends OncePerRequestFilter {

    @Resource
    RedisUtils utils;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(TokenUtil.TOKEN_NAME);
        if(StringUtils.isBlank(token)){
          filterChain.doFilter(request,response);
          return;
        }
        LoginUser loginUser =(LoginUser) utils.get(token);
        if(Objects.isNull(loginUser)){
            filterChain.doFilter(request,response);
            return;
        }

        UsernamePasswordAuthenticationToken userpwd=
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(userpwd);
        filterChain.doFilter(request,response);

    }
}
